<template>
  <div id="app">
    <transition name="slide-fade">
      <template v-if="logined">
        <router-view></router-view>
      </template>
    </transition>
    <template v-if="loginError">
      <div style="text-align:center">
        <span>登陆失败,请稍后重试</span>
      </div>
    </template>

    <div v-transfer-dom>
      <loading v-model="loading"></loading>
    </div>
  </div>
</template>

<script>
import { Loading, TransferDomDirective as TransferDom } from 'vux'
import api from '@/api'
import { wxconfig } from '@/config/sdk'
export default {
  name: 'app',
  data () {
    return {
      loading: true,
      loginError: false,
      logined: false,
      openId: '',
      userId: ''
    }
  },
  directives: {
    TransferDom
  },
  components: {
    Loading
  },
  methods: {
    async login () {
      this.logined = false
      this.loading = true
      // // 先获取openId和userId
      // let {data: {open_id: openId, user_id: userId}} = await api.getOpenId()
      if (window.localStorage.getItem('openId') && window.localStorage.getItem('userId')) {
        this.openId = window.localStorage.getItem('openId')
        this.userId = window.localStorage.getItem('userId')
      } else {
        let {data: {open_id: openId, user_id: userId}} = await api.getOpenId()
        this.openId = openId
        this.userId = userId
      }
      // 通过openId获取token
      let {data: {access_token: accessToken, authorize}} = await api.getUserAuthorize(this.openId)
      window.localStorage.setItem('accessToken', accessToken)
      window.localStorage.setItem('authorize', authorize)
      wxconfig()
      this.logined = true
      this.loading = false
    }
  },
  mounted () {
    this.login()
  }
}
</script>

<style lang="less" >
@import '~vux/src/styles/reset.less';
html,body,#app {
  width: 100%;
  height: 100%;
}

/* 可以设置不同的进入和离开动画 */
/* 设置持续时间和动画函数 */
.slide-fade-enter-active {
  transition: all .2s ease;
}
.slide-fade-leave-active {
  transition: all .2s ease;
}
.slide-fade-enter, .slide-fade-leave-active {
  transform: translateX(10px);
  opacity: 0;
}
</style>
